import React, { useState } from "react";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
  DialogFooter,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
// import { UploadFile, ExtractDataFromUploadedFile } from "@/api/integrations";

import { SafetyRiskPointAPI } from "@/api/SafetyRiskPoint";

import {
  Download,
  Upload,
  Loader2,
  AlertCircle,
  CheckCircle,
  FileX,
  FileSpreadsheet,
} from "lucide-react";

const SafetyRiskPointImportModal = ({ isOpen, onClose, onImportSuccess }) => {
  const [file, setFile] = useState(null);
  const [isProcessing, setIsProcessing] = useState(false);
  const [error, setError] = useState(null);
  const [successMessage, setSuccessMessage] = useState(null);

  const handleFileChange = (e) => {
    setFile(e.target.files[0]);
    setError(null);
    setSuccessMessage(null);
  };

  //  下载文件
  const handleDownloadTemplate = async () => {
    try {
      const response = await SafetyRiskPointAPI.importTemplate();
      const url = window.URL.createObjectURL(new Blob([response]));
      const a = document.createElement("a");
      a.href = url;
      a.download = "危险点导入模板.xlsx";
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      window.URL.revokeObjectURL(url);
    } catch (error) {
      console.error("模板下载失败:", error);
      setError(`模板下载失败: ${error.message || "未知错误"}`);
    }
  };
  const handleImport = async () => {
    if (!file) {
      setError("请先选择一个文件。");
      return;
    }

    setIsProcessing(true);
    setError(null);
    setSuccessMessage(null);

    try {
      const uploadResult = await SafetyRiskPointAPI.import(file);
      setSuccessMessage(`成功导入危险点记录！`);
      setTimeout(() => {
        onImportSuccess();
      }, 1500); // Wait a bit so user can see the success message
    } catch (e) {
      console.error("导入失败:", e);
      setError(e.message);
    } finally {
      setIsProcessing(false);
    }
  };

  return (
    <Dialog open={isOpen} onOpenChange={onClose}>
      <DialogContent className="sm:max-w-[525px]">
        <DialogHeader>
          <DialogTitle>批量导入危险点</DialogTitle>
          <DialogDescription>
            请先下载模板，按照模板格式填写数据后，上传文件进行导入。
          </DialogDescription>
        </DialogHeader>

        <div className="grid gap-4 py-4">
          <Button
            variant="outline"
            onClick={handleDownloadTemplate}
            disabled={isProcessing}
            className="w-full"
          >
            <Download className="mr-2 h-4 w-4" />
            下载导入模板（Excel格式）
          </Button>

          <div className="mt-2 border-2 border-dashed border-gray-300 rounded-lg p-6 transition-all duration-200 hover:border-primary/50 focus-within:border-primary">
            {/* 显示已选择的文件 */}
            {file ? (
              <div className="mt-4 flex items-center justify-between p-3 bg-gray-50 rounded-md">
                <div className="flex items-center">
                  <FileSpreadsheet className="h-5 w-5 mr-2 text-primary" />
                  <span className="text-sm truncate max-w-[200px]">
                    {file.name}
                  </span>
                  <span className="ml-2 text-xs text-gray-500">
                    {(file.size / 1024).toFixed(1)} KB
                  </span>
                </div>
                <Button
                  variant="ghost"
                  size="sm"
                  onClick={() => setFile(null)}
                  className="h-7 w-7 p-0 text-gray-500 hover:text-red-500"
                >
                  <FileX className="h-4 w-4" />
                </Button>
              </div>
            ) : (
              <label
                htmlFor="file-upload"
                className="cursor-pointer flex flex-col items-center justify-center w-full h-full text-center"
              >
                <div className="flex flex-col items-center justify-center pt-5 pb-6">
                  <FileSpreadsheet className="h-10 w-10 mb-3 text-gray-400" />
                  <p className="mb-2 text-sm text-gray-600">
                    <span className="font-semibold">点击上传文件</span>
                  </p>
                  <p className="text-xs text-gray-500">
                    支持 CSV, XLS, XLSX 格式
                  </p>
                </div>
                <Input
                  id="file-upload"
                  type="file"
                  accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
                  onChange={handleFileChange}
                  className="hidden"
                />
              </label>
            )}
          </div>   

          {error && (
            <Alert variant="destructive">
              <AlertCircle className="h-4 w-4" />
              <AlertTitle>导入出错</AlertTitle>
              <AlertDescription>{error}</AlertDescription>
            </Alert>
          )}

          {successMessage && (
            <Alert>
              <CheckCircle className="h-4 w-4 text-green-500" />
              <AlertTitle>导入成功</AlertTitle>
              <AlertDescription>{successMessage}</AlertDescription>
            </Alert>
          )}
        </div>
        <DialogFooter>
          <Button variant="outline" onClick={onClose} disabled={isProcessing}>
            取消
          </Button>
          <Button onClick={handleImport} disabled={isProcessing || !file}>
            {isProcessing ? (
              <>
                <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                正在导入...
              </>
            ) : (
              <>
                <Upload className="mr-2 h-4 w-4" />
                开始导入
              </>
            )}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
};

export default SafetyRiskPointImportModal;
